package com.fastCms.business.frame.busi.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fastCms.business.frame.constant.CommonConst;
import com.fastCms.business.frame.constant.ResultCodeConst;
import com.fastCms.business.frame.exception.BusinessException;
import com.fastCms.business.frame.busi.CloudMenuManageService;
import com.fastCms.business.frame.busi.CloudRoleManageService;
import com.fastCms.business.frame.daos.CloudRoleMenuMapper;
import com.fastCms.business.frame.daos.CloudUserMapper;
import com.fastCms.business.frame.manage.CloudUserManage;
import com.fastCms.business.frame.pojo.entity.CloudRole;
import com.fastCms.business.frame.pojo.entity.CloudUser;
import com.fastCms.business.frame.pojo.entity.CloudUserRoleRel;
import com.fastCms.business.frame.pojo.po.CloudRolePO;
import com.fastCms.business.frame.pojo.po.CloudRoleSavePO;
import com.fastCms.business.frame.pojo.vo.CloudRoleVO;
import com.fastCms.business.frame.pojo.vo.UserSimpleVO;
import com.fastCms.business.frame.service.CloudRoleMenuService;
import com.fastCms.business.frame.service.CloudRoleService;
import com.fastCms.business.frame.service.CloudUserRoleRelService;
import com.fastCms.business.frame.service.CloudUserService;
import com.fastCms.business.frame.service.impl.CloudUserRoleRelServiceImpl;
import com.fastCms.business.frame.utils.BeanConvertUtil;
import com.fastCms.business.frame.utils.CommonsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lsquan
 * @since 2019-03-11
 */
@Component
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CloudRoleManageServiceImpl implements CloudRoleManageService {

    @Autowired
    private CloudUserMapper cloudUserMapper;

    @Autowired
    private CloudRoleService cloudRoleServiceImpl;

    @Autowired
    private CloudRoleMenuMapper cloudRoleMenuMapper;


    @Autowired
    private CloudRoleMenuService cloudRoleMenuServiceImpl;

    @Autowired
    private CloudUserService cloudUserServiceImpl;

    @Autowired
    private CloudMenuManageService cloudMenuManageServiceImpl;

    @Autowired
    private CloudUserRoleRelService cloudUserRoleRelServiceImpl;


    @Override
    public List<CloudRoleVO> showRoles() throws BusinessException {
        String userId = CloudUserManage.getUserId();
        CloudUser cloudUser = cloudUserServiceImpl.findById(userId);
        if (cloudUser == null) {
            log.error("根据userId=" + userId, "------error-----,reason:" + ResultCodeConst.USER.USER_NOT_EXIST_MSG);
            throw new BusinessException(ResultCodeConst.USER.USER_NOT_EXIST_MSG);
        }
        QueryWrapper<CloudRole> cloudRoleWrapper = new QueryWrapper<>();
        cloudRoleWrapper.eq("organize_code", cloudUser.getOrganizeCode());
        cloudRoleWrapper.eq("role_type", 0);
        cloudRoleWrapper.eq("state", CommonConst.STATE.VALID);
        cloudRoleWrapper.orderByDesc("create_time");
        List<CloudRole> list = cloudRoleServiceImpl.list(cloudRoleWrapper);

        List<CloudRoleVO> collect = list.stream().map(cloudRole -> {
            CloudRoleVO cloudRoleVO = new CloudRoleVO();
            BeanUtils.copyProperties(cloudRole, cloudRoleVO);
            return cloudRoleVO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<UserSimpleVO> findUserListByRoleId(String roleId) {
        String organizeCode = CloudUserManage.getOrganizeCode();
        List<CloudUser> cloudUsers = cloudUserMapper.findByRoleId(roleId, organizeCode);
        if (CollectionUtils.isNotEmpty(cloudUsers)) {
            List<UserSimpleVO> collect = cloudUsers.stream().map(cloudUser -> {
                UserSimpleVO userSimpleVO = new UserSimpleVO();
                BeanUtils.copyProperties(cloudUser, userSimpleVO);
                return userSimpleVO;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public boolean deleteRoleAndMenuReal(String roleId) throws BusinessException {
        CloudRole cloudRole = cloudRoleServiceImpl.getById(roleId);

        //根据角色id查询角色下关联人员
        List<CloudUserRoleRel> relations = cloudUserRoleRelServiceImpl.findByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(relations)) {
            throw new BusinessException(ResultCodeConst.USER.ROLE_EXIST_USER, ResultCodeConst.USER.ROLE_EXIST_USER_MSG);
        }
        if (cloudRole != null && cloudRole.getState() == 1) {
            cloudRole.setState(CommonConst.STATE.INVALID);
            boolean a = cloudRoleServiceImpl.saveOrUpdate(cloudRole);
            //删除角色
            int b = cloudRoleMenuMapper.deleteByRoleId(roleId);
            if (a && b != 0) {
                return true;
            }
            return false;
        } else {
            throw new BusinessException(ResultCodeConst.DATA_ERROR, ResultCodeConst.DATA_ERROR_MSG);
        }
    }

    @Override
    public boolean saveOrUpdateRole(CloudRolePO cloudRolePO) throws BusinessException {

        CloudUser cloudUser = cloudUserServiceImpl.findById(cloudRolePO.getUserId());
        if (cloudUser == null) {
            throw new BusinessException(ResultCodeConst.USER.USER_NOT_EXIST, ResultCodeConst.USER.USER_NOT_EXIST_MSG);
        }

        //新增
        if (StringUtils.isBlank(cloudRolePO.getId())) {

            CloudRole cloudRoleExist = cloudRoleServiceImpl.findByRoleName(cloudRolePO.getRoleName(), cloudUser.getOrganizeCode(), cloudUser.getPlatform());
            if (cloudRoleExist != null) {
                throw new BusinessException(ResultCodeConst.USER.ROLE_BE_EXIST, ResultCodeConst.USER.ROLE_BE_EXIST_MSG);
            }
            CloudRole cloudRole = new CloudRole();
            newRole(cloudRole);
            cloudRole.setDescription(cloudRolePO.getDescription());
            cloudRole.setOrganizeCode(cloudUser.getOrganizeCode());
            cloudRole.setRoleName(cloudRolePO.getRoleName());
            cloudRole.setRoleType(0);
            cloudRoleServiceImpl.save(cloudRole);

            //角色分配菜单
            return cloudMenuManageServiceImpl.chooseMenu(cloudRole.getId(), cloudRolePO.getMenuIds());

            //修改
        } else {
            CloudRole cloudRole = cloudRoleServiceImpl.getById(cloudRolePO.getId());
            cloudRole.setDescription(cloudRolePO.getDescription());
            cloudRole.setRoleName(cloudRolePO.getRoleName());
            cloudRoleServiceImpl.saveOrUpdate(cloudRole);
            //角色分配菜单
            return cloudMenuManageServiceImpl.chooseMenu(cloudRole.getId(), cloudRolePO.getMenuIds());
        }
    }

    /**
     * @Description 数据组装
     * @Param [role]
     * @Return void
     * @Date 2019/3/11 下午6:10 lsquan
     */
    public void newRole(CloudRole role) {
        CommonsUtil.initEntity(role);
        role.setRoleCode(role.getId());
    }


}
